﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Text;
using System.Security.Cryptography;
using nspLable.Function.Systems;
using System.Data.SqlClient;
namespace Base
{
    /// <summary>
    /// Common 的摘要说明
    /// </summary>
    public class Common
    {
        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(DateTime DateStr,string DateModel)
        {
            string Restr = "";
            if (DateStr.ToString() != string.Empty )
                switch(DateModel)
                {
                    case "yyyy/MM/dd":
                        Restr = DateStr.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM/dd/yyyy":
                        Restr = DateStr.ToString("MM/dd/yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy-MM-dd":
                        Restr = DateStr.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM-dd-yyyy":
                        Restr = DateStr.ToString("MM-dd-yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy.MM.dd":
                        Restr = DateStr.ToString("yyyy.MM.dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM.dd.yyyy":
                        Restr = DateStr.ToString("MM.dd.yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy年MM月dd日":
                        Restr = DateStr.ToString("yyyy年MM月dd日", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM月dd日yyyy年":
                        Restr = DateStr.ToString("MM月dd日yyyy年", DateTimeFormatInfo.InvariantInfo);
                        break;
                    default :
                        Restr = DateStr.ToShortDateString();
                        break;
                }
            return Restr;
        }

        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(string DateStr, int DateModel)
        {
            string Restr = "";
            if (DateStr != string.Empty)
                switch (DateModel)
                {
                    case 1:
                        Restr = Convert.ToDateTime(DateStr).ToShortDateString();
                        break;
                }
            return Restr;
        }


        public static string ProcessAbsoluteUrl(string strImageURL)
        {
            string strURL = "/Images/System/wutu.gif";
            if (strImageURL != "")
            {
                if (CheckFile(strImageURL))
                    strURL = strImageURL.Replace("../../", Base.BasePage.Config.WebURL).Replace("~/", Base.BasePage.Config.WebURL);
                   // strURL = "../../" + strImageURL;
            }
            return strURL;
        }

        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(string DateStr, string DateModel)
        {
            string Restr = "";
            if (DateStr != string.Empty)
                switch (DateModel)
                {
                    case "yyyy-mm-dd":
                        Restr = Convert.ToDateTime(DateStr).ToShortDateString();
                        break;
                    case "yyyy.MM.dd":
                        Restr = Convert.ToDateTime(DateStr).ToShortDateString();
                        break;
                }
            return Restr;
        }

        /// <summary>
        /// 输出为短日期
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static string GetShortDate(string dateStr)
        {
            if (dateStr != string.Empty)
                return Convert.ToDateTime(dateStr).ToShortDateString();
            else
                return String.Empty;
        }


        /// <summary>
        ///  检测是否全部为数字
        /// </summary>
        /// <param name="num">要检测的字符串</param>
        /// <returns></returns>
        public static Boolean CheckNum(string num)
        {
            return Regex.IsMatch(num, @"^\+?[0-9][0-9]*$");
        }


        /// <summary>
        /// 中文检测
        /// </summary>
        /// <param name="strTest"></param>
        /// <returns></returns>
        public static Boolean IsIncludeChineseCode(string strTest)
        {
            return Regex.IsMatch(strTest, @"[\u4e00-\u9fa5]+");
        }


        /// <summary>
        /// 取得指定字符之间的字符串
        /// </summary>
        /// <param name="str">要查找的字符串</param>
        /// <param name="StartStr">起始字符</param>
        /// <param name="EndStr">结束字符</param>
        /// <returns></returns>
        public string GetString(string str, string StartStr, string EndStr)
        {
            int intStart = 0;
            int intEnd = 0;

            if (str == string.Empty || StartStr == string.Empty || EndStr == string.Empty)
                return str;
            else
            {
                intStart = str.IndexOf(StartStr);
                intEnd = str.IndexOf(EndStr);
                if (intStart > intEnd)
                    return str;
                else
                    return str.Substring(intStart, intEnd);
            }

        }


        /// <summary>
        /// 取得指定字符之间的字符串
        /// </summary>
        /// <param name="str">要查找的字符串</param>
        /// <param name="StartStr">起始字符</param>
        /// <param name="EndStr">结束字符</param>
        /// <returns></returns>
        public static string GetString(string str, int startIndex, int Length)
        {
            int intStart = 0;
            int intEnd = 0;
            if (startIndex > 0) intStart = startIndex;
            if(Length>0) intEnd=Length;
            if (intEnd > intStart)
                if (str.Length < Length)
                    return str.Substring(intStart);
                else
                    return str.Substring(intStart, Length);
            else
                return str.Substring(intStart);

        }


        /// <summary>
        /// 过滤JS脚本
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public  string WipeScript(string html)
        {
            Regex regex1 = new Regex(@"<script[/s/S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(@" href *= *[/s/S]*script *:", RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(@" on[/s/S]*=", RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(@"<iframe[/s/S]+</iframe *>", RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(@"<frameset[/s/S]+</frameset *>", RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记 
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 
            html = regex4.Replace(html, ""); //过滤iframe 
            html = regex5.Replace(html, ""); //过滤frameset 
            return html;
        }


        /// <summary>
        /// 清除HTML所有格式
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string ClearHtml(string strHtml)
        {
            if (strHtml != "")
            {
                Regex regex = null;
                Match match = null;
                regex = new Regex(@"<\/?[^>]*>", RegexOptions.IgnoreCase);
                for (match = regex.Match(strHtml); match.Success; match = match.NextMatch())
                {
                    strHtml = strHtml.Replace(match.Groups[0].ToString(), "");
                }
            }
            return strHtml;
        }


        /// <summary>
        /// 清除编辑器中的非法字符串
        /// </summary>
        /// <param name="strHTML"></param>
        /// <returns></returns>
        public static string RemoveHTMLForEditor(string strHTML)
        {
            string input = strHTML;
            Regex regex = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(@" no[\s\S]*=", RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(@"<iframe[\s\S]+</iframe *>", RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(@"<frameset[\s\S]+</frameset *>", RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(@"<div[\s\S]+</div *>", RegexOptions.IgnoreCase);
            input = regex.Replace(input, "");
            input = regex2.Replace(input, " _disibledevent=");
            input = regex3.Replace(input, "");
            input = regex4.Replace(input, "");
            return regex5.Replace(input, "");
        }


        /// <summary>
        /// 清除HTML指定格式
        /// </summary>
        /// <param name="strHTML"></param>
        /// <returns></returns>
        public static string RemoveHTML(string strHTML)
        {
            string input = strHTML;
            Regex regex = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(@" href *= *[\s\S]*script *:", RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(@" no[\s\S]*=", RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(@"<iframe[\s\S]+</iframe *>", RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(@"<frameset[\s\S]+</frameset *>", RegexOptions.IgnoreCase);
            Regex regex6 = new Regex(@"\<img[^\>]+\>", RegexOptions.IgnoreCase);
            Regex regex7 = new Regex("</p>", RegexOptions.IgnoreCase);
            Regex regex8 = new Regex("<p>", RegexOptions.IgnoreCase);
            Regex regex9 = new Regex("<[^>]*>", RegexOptions.IgnoreCase);
            Regex regex10 = new Regex(@"<table[\s\S]+</table *>", RegexOptions.IgnoreCase);
            Regex regex11 = new Regex(@"<div[\s\S]+</div *>", RegexOptions.IgnoreCase);
            input = regex.Replace(input, "");
            input = regex2.Replace(input, "");
            input = regex3.Replace(input, " _disibledevent=");
            input = regex4.Replace(input, "");
            input = regex5.Replace(input, "");
            input = regex6.Replace(input, "");
            input = regex7.Replace(input, "");
            input = regex8.Replace(input, "");
            input = regex9.Replace(input, "");
            input = regex10.Replace(input, "");
            return regex11.Replace(input, "").Replace(" ", "").Replace("</strong>", "").Replace("<strong>", "");
        }
        /// <summary>
        /// 过滤掉不合格的字符
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static string Filtrate(string strSource)
		{
			strSource=strSource.Replace("'","");
			strSource=strSource.Replace("\"","");
			strSource=strSource.Replace("<","");
			strSource=strSource.Replace(">","");
			strSource=strSource.Replace("=","");
			strSource=strSource.Replace("or","");
			strSource=strSource.Replace("select","");	
			strSource=strSource.Trim();
			return strSource;

		}

        /// <summary>
        /// 检测提交页面是否含有非法的SQL字符
        /// </summary>
        /// <returns></returns>
        public static bool CheckBadForm()
        {
            if (HttpContext.Current.Request.Form.Count > 0)
            {
                for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
                {
                    if (CheckBadWord(HttpContext.Current.Request.Form[i]))
                        return true;
                }
            }
            return false;
        }


        /// <summary>
        ///  非法SQL字符检测
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool CheckBadWord(string str)
        {
            string pattern = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec   master|netlocalgroup administrators|net user|or|and";
            if (Regex.IsMatch(str, pattern, RegexOptions.IgnoreCase) )
                
                return true;
            return false;
        }


        /// <summary>
        /// Email 检测
        /// </summary>
        /// <param name="strEmail">待检测的Email</param>
        /// <returns>{true,false}</returns>
        public bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        /// <summary>
        /// 价格的检查
        /// </summary>
        /// <param name="strPrice"></param>
        /// <returns></returns>
        public bool IsValidPrice(String strPrice) {

            return Regex.IsMatch(strPrice, @"\d+(\.){0,1}\d{0,2}");
        }
        /// <summary>
        /// 随机生成任意长度的字符串
        /// </summary>
        /// <param name="NumLength">生成的长度</param>
        /// <returns></returns>
        public string GetRandom(int NumLength)
        {
            string rnd = "";
            for (int i = 0; i < NumLength; i++)
            {
                int strRnd = new Random().Next(1, 99);
                rnd += strRnd.ToString();
            }    
            return rnd;
        }


        /// <summary>
        /// 格式化字节大小
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string FormatBytesStr(int bytes)
        {
            if (bytes > 0x40000000)
            {
                double num = bytes / 0x40000000;
                return (num.ToString("0") + "G");
            }
            if (bytes > 0x100000)
            {
                double num2 = bytes / 0x100000;
                return (num2.ToString("0") + "M");
            }
            if (bytes > 0x400)
            {
                double num3 = bytes / 0x400;
                return (num3.ToString("0") + "K");
            }
            return (bytes.ToString() + "Bytes");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="fString"></param>
        /// <returns></returns>
       /* public static string changechr(string fString)
        {
            if (fString==string.Empty) 
            {          
               fString = fString.Replace( "--", "——");  
               fString = fString.Replace( "%20", "");    
               fString = fString.Replace("==", "");     
               fString = fString.Replace( CHR(32), " ");	 
               fString = fString.Replace( CHR(9), " ");			 
               fString = fString.Replace( CHR(34), "&quot;");
               fString = fString.Replace( CHR(39), "&#39;");	 
               fString = fString.Replace( CHR(13), "");
               fString = fString.Replace( CHR(10) & CHR(10), "</P><P> ");
               fString = fString.Replace( CHR(10), "<BR> ");
            }
            return fString.Trim().ToString();
        }*/


        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="path">虚拟路径</param>
        /// <returns></returns>
        public static bool FileDelete(string path)
        {

            string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());

            bool ret = false;
            //../../
            //../../../
            path = path.Replace("../../..", "");
            path = path.Replace("../..", "");
            path = path.Replace("\\", "/");

            string paths = tmpRootDir + path.Replace(@"/", @"\"); //转换成绝对路
            paths = paths.Replace("\\\\", "\\");
            System.IO.FileInfo file = new System.IO.FileInfo(paths);
            if (System.IO.File.Exists(paths))
            {
                file.Delete();
                ret = true;
            }
            return ret;
        }


        /// <summary>
        /// 处理图片路径
        /// </summary>
        /// <param name="strImageURL"></param>
        /// <returns>返回绝对路径</returns>
        public static string ProcessImageUrl(string strImageURL)
        {
            string strURL = "{pb_weburl}Images/System/wutu.gif";
            if (strImageURL != "")
            {
                if (CheckFile(strImageURL))
                    strURL = strImageURL.Replace("~/", Base.BasePage.Config.WebURL).Replace("../../", Base.BasePage.Config.WebURL);
                else
                    strURL = "../../Images/System/wutu.gif";
            }
            return strURL;

        }

        /// <summary>
        /// 检测文件是否存在
        /// </summary>
        /// <param name="FileUrl">模板路径</param>
        /// <returns></returns>
        private static bool CheckFile(string FileUrl)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + FileUrl.Replace("~/", "/").Replace("../../", "/");
            if (System.IO.File.Exists(path))
                return true;
            else
                return false;
        }


        /// <summary>
        /// 对字符串进行MD5编码
        /// </summary>
        /// <param name="xStr">预加密的原字符串</param>
        /// <returns>编码后的MD5密码串</returns>
        public static string SysEncode(string xStr)
        {
            string str = "";
            try
            {               
                str = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(xStr, "md5").ToString();
            }
            catch
            {
                return xStr;
            }
            return str;     //返回加密后的字符串
        }

        //判断日期格式 如:2008-1-20 或2008-01-20 而且包含了对不同年份2月的天数，闰年的控制等等：
        public static bool isDataTime(string datetime)
        {
            return Regex.IsMatch(datetime, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
        }
        //判断密码格式
        public static bool isPassPwd(string pass)
        {
            return Regex.IsMatch(pass, @"^[0-9a-zA-Z_]{6,20}$");
        }
        //固定电话号码格式
        public static bool isTel(string strTel)
        {
            return Regex.IsMatch(strTel, @"^\d{7,15}$");
        }
        //手机号码格式
        public static bool isCellphone(string strCellphone)
        {
            return Regex.IsMatch(strCellphone, @"^\d{11}|\d{12}$");
        }
        //邮政编码格式
        public static bool isPostCode(string strPostCode)
        {
            return Regex.IsMatch(strPostCode, @"^\d{6}$");
        }
        //判断身份证格式
        public static bool isIdCard(string strIdCard)
        {
            return Regex.IsMatch(strIdCard, @"^\d{15}|\d{18}$");
        }
        //判断邮箱格式
        public  static bool  isMail(string strEMail)
        {
            return Regex.IsMatch(strEMail, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
        }
        //判断用户名称格式
        public  static bool isUserName(string name)
        {
            return Regex.IsMatch(name, @"^[0-9a-zA-Z_]{6,20}$");
        }
        //真实姓名长度
        public  static bool isUName(string strName)
        {
            return Regex.IsMatch(strName, @"^(\s|\S){2,20}$");
        }
        //问题答案长度
        public  static bool isAnswer(string strAnswer)
        {
            return Regex.IsMatch(strAnswer, @"^(\s|\S){3,35}$");
        }
        //地址长度
        public  static bool isAddress(string strAddress)
        {
            return Regex.IsMatch(strAddress, @"^(\s|\S){4,100}$");
        }
        //业务简介长度
        public  static bool isBFairsInfo(string strBFairsInfo)
        {
            return Regex.IsMatch(strBFairsInfo, @"^(\s|\S){3,200}$");
        }
        //企业简介长度
        public  static bool isBComInfo(string strBComInfo)
        {
            return Regex.IsMatch(strBComInfo, @"^(\s|\S){3,500}$");
        }
        public  static bool isBComInfo1(string strBComInfo)
        {
            return Regex.IsMatch(strBComInfo, @"^(\s|\S){3,3000}$");
        }
        public  static bool isBComInfo2(string strBComInfo)
        {
            return Regex.IsMatch(strBComInfo, @"^(\s|\S){3,3000}$");
        }
        //验证内容长度
        public  static bool isContent(string strContent)
        {
            return Regex.IsMatch(strContent, @"^(\s|\S){2,5000}$");
        }
        //验证InternetURL
        public  static bool isUrl(string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$");
        }
        //必须为数字
        public  static bool isNum(string strNum)
        {
            return Regex.IsMatch(strNum, @"^\+?[1-9][0-9]*$");
        }
        //验证价格
        public  static bool isProce(string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^(0|[1-9]\d*)(\.\d{1,2})?$");
        }

        /// <summary>
        /// MD5 16位加密
        /// </summary>
        /// <param name="STR">要加密的字符串</param>
        /// <returns></returns>  
        public static string Encryption(string STR)
        {
            string password = "";
            STR = STR + BasePage.Config.Encryption;
            //pwd为加密结果
            MD5 ps = MD5.Create();
            byte[] s = ps.ComputeHash(Encoding.UTF8.GetBytes(STR));
            //这里的UTF8是编码方式，你可以采用你喜欢的方式进行，比如UNcode等等
            for (int i = 0; i < s.Length; i++)
            {
                password = password + s[i].ToString();
            }
            return password;
        }

        /// <summary>
        /// 读取
        /// </summary>
        public static string GetBottom(string str)
        {
            string Restr = "";
            nspLable.Manage.TUserLable Temp = new nspLable.Manage.RUserLable().GateItem(str);
            if (Temp.Info == null || Temp.Info == "")
                return str;
            else
                Restr = Temp.Info.ToString();
            Restr = Restr.Replace("{pb_weburl}", BasePage.Config.WebURL);
            String s = "{PB_weblogo}|{PB_WebURL}|{PB_Searchinfo}|{PB_keyword}|{pb_weburl}|{PB_WEBTEL}|{PB_POSTFIX}|";
            Tempinc t = new Tempinc("a");
            string st = "";
            st = t.PBFunction(Restr, s);
            Restr = t.PBFunction(st, s);
            return Restr;
        }

        public static bool GetConnectionState(string serverName,string UserName,string Password,string DataName)
        {
            SqlConnection connection = new SqlConnection("Data Source=" + serverName + "; User ID=" + UserName + "; Password=" + Password + "; Initial Catalog=" + DataName);
            try
            {
                connection.Open();
                if (connection.State != ConnectionState.Open)
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
    }

    public class SQLFlag : ConfigurationElement
    {
        [ConfigurationProperty("flag", IsRequired = true)]
        public string _SQLFlag
        {
            get { return this["flag"] as string; }
        }
        [ConfigurationProperty("endDate")]
        public string _EndDate
        {
            get {return this["endDate"] as string;}
        }
        [ConfigurationProperty("AdminName")]
        public string _AdminName
        {
            get { return this["AdminName"] as string; }
        }
    }
    public class SafeSetting : ConfigurationSection
    {
        [ConfigurationProperty("siteName", IsRequired = true)]
        public string SiteName
        {
            get { return this["siteName"] as string; }
        }
        [ConfigurationProperty("SQLFlag")]
        public SQLFlag sqlFlag
        {
            get { return this["SQLFlag"] as SQLFlag; }
        }

    }
}